package scanner

import (
	"io/ioutil"
	"learning/gooop/spring/autogen/domain"
	"path/filepath"
	"strings"
)

type IPackageScanner interface {
	ScanPackage(project *domain.ProjectInfo, parent *domain.PackageInfo, dir string) (error, *domain.PackageInfo)
}

type tPackageScanner int

func (me *tPackageScanner) ScanPackage(project *domain.ProjectInfo, parent *domain.PackageInfo, dir string) (error, *domain.PackageInfo) {
	pkg := domain.NewPackageInfo()
	pkg.Project = project
	pkg.Parent = parent
	pkg.LocalDir = dir

	_, f := filepath.Split(dir)
	pkg.Name = f

	files, e := ioutil.ReadDir(dir)
	if e != nil {
		return e, nil
	}

	for _, file := range files {
		if file.IsDir() {
			e, p := me.ScanPackage(project, pkg, dir+"/"+file.Name())

			if e != nil {
				return e, nil

			} else if p != nil {
				pkg.AppendPackage(p)
			}

		} else if strings.HasSuffix(file.Name(), ".go") {
			e, f := DefaultFileScanner.ScanCodeFile(pkg, dir+"/"+file.Name())

			if e != nil {
				return e, nil

			} else if f != nil {
				pkg.AppendFile(f)
			}
		}
	}

	return nil, pkg
}

var DefaultPackageScanner IPackageScanner = new(tPackageScanner)
